local skynet = require "skynet"
require "skynet.manager"
local db   = require "dblib"
local CMD = {}

local DB={}

function DB.AddParaIn(querymsg, arg)
    arg = arg or ""
    querymsg = querymsg..string.format("\""..arg.."\",")
	return querymsg
end

function DB.AddParaOut(querymsg, arg)
	querymsg = querymsg..arg
	return querymsg
end

-- 创建账号
function CMD.OnUserCreateReq(sex, logintype, nickname, url, password, client, openid)
   
    local queryout = ""
    local queryin
    local strpass=string.sub(password,1,string.find(password,string.char(0))-1)   
    if logintype == 1 then --微信登录 
        local stropenid=string.sub(openid,1,string.find(openid,string.char(0))-1)
        queryin = "call  Pr_UserWeiXinCreate6("
        queryin = DB.AddParaIn(queryin, stropenid)
        queryin = DB.AddParaIn(queryin, strpass)
        queryin = DB.AddParaIn(queryin, nickname)
        queryin = DB.AddParaIn(queryin, client)
        queryin = DB.AddParaIn(queryin, url)
      
        queryout = DB.AddParaOut(queryout, "@GoldRankPos,")
        queryout = DB.AddParaOut(queryout, "@ExGoldCount,")
        queryout = DB.AddParaOut(queryout, "@UserSign,")
        
    else
        queryin = "call  Pr_UserYouKeCreate4("
        queryin = DB.AddParaIn(queryin, strpass)
        queryin = DB.AddParaIn(queryin, nickname)
        queryin = DB.AddParaIn(queryin, client)
    end
    
    queryout = DB.AddParaOut(queryout, "@PlayerId,")
    queryout = DB.AddParaOut(queryout, "@CardCount,")
    queryout = DB.AddParaOut(queryout, "@JinBi,")
    queryout = DB.AddParaOut(queryout, "@ExtentCode,")
    queryout = DB.AddParaOut(queryout, "@FirstCreate,")
    queryout = DB.AddParaOut(queryout, "@ErrMsg,")
    queryout = DB.AddParaOut(queryout, "@returnval")
      
    local res0, res = db.call(queryin..queryout..");", "select "..queryout)
    
    local result    = {nPlayerId=nil, nDiamond=nil, llJinBi=nil, nSex=nil, nLoginType=nil, nScore=nil, szName=nil, szHeadUrl=nil, szPass=nil, 
                        szClient=nil, szErrMsg=nil, szSign=nil,bSucc=nil, nExternCode=nil, nFirstCreate=nil, nGoldRankPos=nil, llExGoldCount=nil}
    result.nPlayerId    = res[1]['@PlayerId']
    result.nDiamond     = res[1]['@CardCount']
    result.llJinBi      = res[1]['@JinBi']
    result.nSex         = sex
    result.nLoginType   = logintype
    result.nScore       = 0
    result.szName       = nickname
    result.szHeadUrl    = url
    result.szPass       = strpass
    result.szClient     = client
    result.nExternCode  = res[1]['@ExtentCode']
    result.nFirstCreate = res[1]['@FirstCreate']
    
    if logintype == 1 then --微信登录
        result.nGoldRankPos  = res[1]['@GoldRankPos']
        result.llExGoldCount = res[1]['@ExGoldCount']
        result.szSign        = res[1]['@UserSign']
    else
        result.nGoldRankPos  = 0
        result.llExGoldCount = 0
        result.szSign        = ""
    end
    
    result.szErrMsg = res[1]['@ErrMsg']   
    result.bSucc    = res[1]['@returnval']

    return result
end

-- 登录
function CMD.OnUserLoginReq(play_id, sex, logintype, nickname, url, password, client)
   
    local strpass=string.sub(password,1,string.find(password,string.char(0))-1)
    local queryin = "call  Pr_UserLogin5("
    queryin = DB.AddParaIn(queryin, play_id)
    queryin = DB.AddParaIn(queryin, strpass)
    queryin = DB.AddParaIn(queryin, nickname)
    queryin = DB.AddParaIn(queryin, client)
    queryin = DB.AddParaIn(queryin, url)
    
    local queryout = ""
	queryout = DB.AddParaOut(queryout, "@CardCount,")
    queryout = DB.AddParaOut(queryout, "@JinBi,")
    queryout = DB.AddParaOut(queryout, "@FirstLogin,")
    queryout = DB.AddParaOut(queryout, "@PoChanJinBi,")
    queryout = DB.AddParaOut(queryout, "@ExtentCode,")
    queryout = DB.AddParaOut(queryout, "@UserSign,")
    queryout = DB.AddParaOut(queryout, "@GoldRankPos,")
    queryout = DB.AddParaOut(queryout, "@ExGoldCount,")
    queryout = DB.AddParaOut(queryout, "@ErrMsg,")
    queryout = DB.AddParaOut(queryout, "@returnval")

    local res0, res = db.call(queryin..queryout..");", "select "..queryout)

    local result = {nPlayerId=nil, nDiamond=nil, nSex=nil, nLoginType=nil, nScore=nil, nFirstLogin=nil, nPoChanJinBi=nil, llJinBi=nil, szName=nil,
                    szHeadUrl=nil, szPass=nil, szClient=nil, szSign=nil, szErrMsg=nil, bSucc=nil, nExternCode=nil, nGoldRankPos=nil, llExGoldCount=nil}
    
    result.nPlayerId        = play_id
    result.nDiamond         = res[1]['@CardCount']
    result.nScore           = 0
    result.llJinBi          = res[1]['@JinBi']
    result.nFirstLogin      = res[1]['@FirstLogin']
    result.nPoChanJinBi     = res[1]['@PoChanJinBi']
    result.nLoginType       = logintype
    result.nSex             = sex
    result.szName           = nickname
    result.szHeadUrl        = url
    result.szPass           = strpass
    result.szClient         = client
    result.szSign           = res[1]['@UserSign']
    result.nGoldRankPos     = res[1]['@GoldRankPos']
    result.llExGoldCount    = res[1]['@ExGoldCount']
    result.nExternCode      = res[1]['@ExtentCode']
    result.szErrMsg         = res[1]['@ErrMsg']
    result.bSucc            = res[1]['@returnval']  
    return result
   
end

-- 写战绩扩展 ,小局结算
function CMD.OnWriteZhanJiEx(zhji)
    skynet.error("[sql] OnWriteZhanJiEx")
    local queryin = "call  Pr_WriteUserZhanJi3("

    queryin = DB.AddParaIn(queryin, zhji.m_nGameId)
    queryin = DB.AddParaIn(queryin, zhji.nTableId)
    queryin = DB.AddParaIn(queryin, zhji.nPlayerId)
    queryin = DB.AddParaIn(queryin, zhji.szNickName)
    queryin = DB.AddParaIn(queryin, zhji.szStarTime)
    queryin = DB.AddParaIn(queryin, zhji.szEndTime)
    queryin = DB.AddParaIn(queryin, zhji.szRecToken)
    queryin = DB.AddParaIn(queryin, zhji.nDiFen)
    queryin = DB.AddParaIn(queryin, zhji.jushu)
    queryin = DB.AddParaIn(queryin, zhji.nTotalJu)
    queryin = DB.AddParaIn(queryin, zhji.fuju)
    queryin = DB.AddParaIn(queryin, zhji.fuType)
    queryin = DB.AddParaIn(queryin, zhji.fuFangShi)
    queryin = DB.AddParaIn(queryin, zhji.zhangjia)
    
    for i=1, 8 do    
        queryin = DB.AddParaIn(queryin, zhji.nPlayerIdArr[i])
        queryin = DB.AddParaIn(queryin, zhji.nArrowArr[i])
        queryin = DB.AddParaIn(queryin, zhji.nScores[i])
        queryin = DB.AddParaIn(queryin, zhji.szNames[i]) 
    end
    
    for i=1, 8 do    
        queryin = DB.AddParaIn(queryin, zhji.mingGanArr[i])
    end
    
    for i=1, 8 do    
        queryin = DB.AddParaIn(queryin, zhji.anganArr[i])
    end
    
    queryin = DB.AddParaIn(queryin, zhji.wMyChairId)
    queryin = DB.AddParaIn(queryin, zhji.bEndJu)
    
    local queryout = ""
	queryout = DB.AddParaOut(queryout, "@intOutIdx,")
    queryout = DB.AddParaOut(queryout, "@returnval")
    
    local res0, res = db.call(queryin..queryout..");", "select "..queryout)
    
    local result = {intOutIdx = nil, returnval = nil}
    result.intOutIdx=res[1]['@intOutIdx']
    result.bSucc=res[1]['@returnval']
    
    return result
end

-- 写战绩 , 大局结算
function CMD.WriteZhanJiDb(ZhanJiTmp)
     skynet.error("[sql] WriteZhanJiDb")
    local queryin = "call  Pr_WriteZhanJi3("

    queryin = DB.AddParaIn(queryin, ZhanJiTmp.nPlayerId)
    queryin = DB.AddParaIn(queryin, ZhanJiTmp.nGameId)
    queryin = DB.AddParaIn(queryin, ZhanJiTmp.nTableId)
    queryin = DB.AddParaIn(queryin, ZhanJiTmp.wMyChairId)
    
    for i = 1, 8 do 
        queryin = DB.AddParaIn(queryin, ZhanJiTmp.nScore[i])
    end
  
    for i = 1, 8 do 
        queryin = DB.AddParaIn(queryin, ZhanJiTmp.szName[i])
    end
    queryin = DB.AddParaIn(queryin, ZhanJiTmp.szAnsiTime)
    
    local queryout = ""
	queryout = DB.AddParaOut(queryout, "@intOutIdx,")
    queryout = DB.AddParaOut(queryout, "@returnval")
    
    local res0, res = db.call(queryin..queryout..");", "select "..queryout)
    
    local result        = {intOutIdx = nil, returnval = nil}
    result.intOutIdx    = res[1]['@intOutIdx']
    result.bSucc        = res[1]['@returnval']
    
    return result
     
end

-- 用户获取战绩
function CMD.OnNetMsgPlayerZhanjiReq(play_id)
    skynet.error("[sql] OnNetMsgPlayerZhanjiReq")

    local res = db.call("call  Pr_LoadZhanJi4("..play_id..")")

    local result = {nPlayerId = nil, nCount = nil, OneZhanJiList = {}, bSucc = nil}
    
    if #res[1] == 0 then  -- 返回列表长度
        result.bSucc = false
        return result
    end
    
    local count = 0    
    result.nPlayerId = play_id
    for index,table_obj in pairs(res[1]) do 
        count = count + 1
        local OneZhanJi = {nIdx = nil, nTableId = nil, wMyChairId = nil, nRound = nil, nGameId = nil, szTime = nil,szNames = {}, nScores = {}}
        OneZhanJi['nIdx'] = table_obj['@intOutIdx']
        OneZhanJi['nTableId'] = table_obj['@intOutTableId']
        OneZhanJi['wMyChairId'] = table_obj['@intOutMyChair']
        OneZhanJi['nRound'] = table_obj['@intTotalRound']
        OneZhanJi['nGameId'] = table_obj['@intOutGameID']        
        OneZhanJi['szTime'] = table_obj['@szOutTime']
        table.insert(OneZhanJi.szNames,table_obj['@szChair0Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair1Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair2Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair3Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair4Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair5Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair6Name'])
        table.insert(OneZhanJi.szNames,table_obj['@szChair7Name'])
        
        table.insert(OneZhanJi.nScores,table_obj['@intChair0Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair1Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair2Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair3Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair4Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair5Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair6Score'])
        table.insert(OneZhanJi.nScores,table_obj['@intChair7Score'])

        table.insert(result.OneZhanJiList,OneZhanJi)

    end
    result.nCount = count
    result.bSucc = true    
    return result

end

-- 获取系统信息
function CMD.OnGetSystemMsg()
    
    local queryin = "call  Pr_GetSystemMsg(" 
    local queryout = ""
	queryout = DB.AddParaOut(queryout, "@ShowFangKa,")
    queryout = DB.AddParaOut(queryout, "@StopSvr,")
    queryout = DB.AddParaOut(queryout, "@Msg,")
    queryout = DB.AddParaOut(queryout, "@WeiXinMsg,")
    queryout = DB.AddParaOut(queryout, "@StopSvrMsg,")
    queryout = DB.AddParaOut(queryout, "@returnval")
    local res0, res = db.call(queryin..queryout..");", "select "..queryout)
end

function CMD.OnSubPlayerCardCount(play_id, count)
    skynet.error("[sql] OnSubPlayerCardCount", play_id, count )
    db.call("call  Pr_SubPlayerCard("..play_id..","..count..")")
end

skynet.start(function()
    skynet.error("sql server start...")
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)   
    skynet.register ".sql"
    
    math.randomseed(os.time())
end)

